﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Threading;
using System.Net;
using System.Net.Sockets;

using Azku.Common;


namespace Azku.ServiceUtil
{
    public class Service : IDisposable
    {
        private static int m_ThreadNumber = 5;
        private Thread[] m_ThreadArry = new Thread[m_ThreadNumber];

        private int m_HostPort = 9999;//服务监听端口

        public int HostPort
        {
            get { return m_HostPort; }
            set { m_HostPort = value; }
        }
        private UdpClient m_UdpClient = null;

        private ErrorLog m_ErrorLog;

        public ErrorLog ErrorLog
        {
            get { return m_ErrorLog; }
            set { m_ErrorLog = value; }
        }

        public Service()
        {
            m_UdpClient = new UdpClient(HostPort);
        }

        public Service(int hostPort)
            : this()
        {
            HostPort = hostPort;
        }

        public void ThreadStart()
        {
            for (int i = 0; i < m_ThreadNumber; i++)
            {
                Thread tempThread = new Thread(Listener);
                tempThread.IsBackground = true;
                tempThread.Start();
                m_ThreadArry[i] = tempThread;
            }
        }

        private void Listener()
        {
            while (true)
            {
                try
                {
                    IPEndPoint pIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    Byte[] buffer = m_UdpClient.Receive(ref pIPEndPoint);

                    object pReceiveObj = Common.ZipSerializable.DeserializeObject(buffer);
                    if (pReceiveObj != null)
                    {
                        if (pReceiveObj is CTSMessageBase)
                        {
                            CTSMessageBase pCTSUserLogin = (CTSMessageBase)pReceiveObj;
                            pCTSUserLogin.M_IPEndPoint = pIPEndPoint;
                            DataManager.Instance.MessageCollection.Insert(pCTSUserLogin);

                            ErrorLog(string.Format("Receive Msg From IP:{0} Port:{1}", pIPEndPoint.Address.ToString(), pIPEndPoint.Port));
                        }
                    }
                }
                catch (Exception ex)
                {
                    ErrorLog(ex.Message);
                }
            }
        }


        #region IDisposable 成员

        public void Dispose()
        {
            for (int i = 0; i < m_ThreadNumber; i++)
            {
                m_ThreadArry[i].Abort();
            }
            m_UdpClient.Close();
        }

        #endregion
    }
}
